"""
# 使用Python计算简单图像梯度
"""

import matplotlib.pyplot as plt
import numpy as np
from skimage import data, color

# 加载示例图像，并转换为灰度模式
image = color.rgb2gray(data.chelsea())

# 使用中心化的一维滤波器计算水平梯度
# 这等价于将每个非边界像素替换为它的左侧相邻像素和右侧相邻像素的差，最左边和最右边上的像素的梯度是0
gx = np.empty(image.shape, dtype=np.double)
gx[0, :] = 0
gx[:, -1] = 0
gx[:, 1:-1] = image[:, :-2] - image[:, 2:]

# 以同样的方式计算垂直梯度
gy = np.empty(image.shape, dtype=np.double)
gy[0, :] = 0
gy[-1, :] = 0
gy[1:-1, :] = image[:-2, :] - image[2:, :]

fig, (ax_orig, ax_horizon, ax_vertical) = plt.subplots(3, 1, figsize=(5, 9), sharex=True, sharey=True)
ax_orig.axis('off')
ax_orig.imshow(image, cmap=plt.cm.gray)
ax_orig.set_title('Original image')
ax_orig.set_adjustable('box')

ax_horizon.axis('off')
ax_horizon.imshow(gx, cmap=plt.cm.gray)
ax_horizon.set_title('Horizontal image')
ax_horizon.set_adjustable('box')

ax_vertical.axis('off')
ax_vertical.imshow(gy, cmap=plt.cm.gray)
ax_vertical.set_title('Vertical image')
ax_vertical.set_adjustable('box')

fig.show()